package com.shinewind.sso.config;

import com.shinewind.sso.filter.MyAdminJwtAuthFilter;
import com.shinewind.sso.filter.MyJwtAuthFilter;
import com.shinewind.sso.filter.MyVerifyCodeFilter;
import com.shinewind.sso.handler.*;
import com.shinewind.sso.service.MyUserDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
@Slf4j
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyVerifyCodeFilter verifyCodeFilter;
    @Autowired
    private MyUserDetailService userDetailService;
    @Autowired
    private AccessDenyHandler accessDenyHandler;
    @Autowired
    private AuthEntryPointHandler authEntryPointHandler;
    @Autowired
    private LoginOutSuccessHandler loginOutSuccessHandler;
    @Autowired
    private LoginSuccessHandler loginSuccessHandler;
    @Autowired
    private LoginFailureHandler loginFailureHandler;
    @Autowired
    private AdminLoginSuccessHandler adminLoginSuccessHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        MyJwtAuthFilter jwtAuthFilter = new MyJwtAuthFilter(authenticationManager());
        jwtAuthFilter.setAuthenticationSuccessHandler(loginSuccessHandler);
        jwtAuthFilter.setAuthenticationFailureHandler(loginFailureHandler);
        MyAdminJwtAuthFilter adminJwtAuthFilter = new MyAdminJwtAuthFilter(authenticationManager());
        adminJwtAuthFilter.setAuthenticationSuccessHandler(adminLoginSuccessHandler);
        adminJwtAuthFilter.setAuthenticationFailureHandler(loginFailureHandler);
        http.authorizeRequests()
                .antMatchers("/sso/model/register").permitAll()
                .antMatchers("/sso/model/logout").permitAll()
                .antMatchers("/sso/**").permitAll()
                .antMatchers("/swagger/**",
                                        "/swagger-ui.html",
                                        "/swagger-ui/**",
                                        "/webjars/**",
                                        "/v2/**",
                                        "/v3/**",
                                        "/v2/api-docs-ext/**",
                                        "/swagger-resources/**",
                                        "/doc.html").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginProcessingUrl("/sso/model/login")
                .and()
                .addFilterBefore(verifyCodeFilter,UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(jwtAuthFilter,UsernamePasswordAuthenticationFilter.class)
                .exceptionHandling()
                .accessDeniedHandler(accessDenyHandler) //授权异常处理
                .authenticationEntryPoint(authEntryPointHandler) //认证异常处理
                .and()
                .logout()
                .logoutUrl("/sso/model/logout")
                .logoutSuccessHandler(loginOutSuccessHandler) //退出登录
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS) //关闭session
                .and()
                .cors()
                .and()
                .csrf().disable()
                //管理员登录
                .formLogin()
                .loginProcessingUrl("/sso/admin/model/sign")
                .and()
                .addFilterBefore(adminJwtAuthFilter,UsernamePasswordAuthenticationFilter.class)
                .exceptionHandling()
                .accessDeniedHandler(accessDenyHandler) //授权异常处理
                .authenticationEntryPoint(authEntryPointHandler) //认证异常处理
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS) //关闭session
                .and()
                .cors()
                .and()
                .csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService)
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        List<AuthenticationProvider> providers = new ArrayList<>();
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        daoAuthenticationProvider.setUserDetailsService(userDetailService);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        providers.add(daoAuthenticationProvider);
        return new ProviderManager(providers);
    }
}
